package cn.fl.customer.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.fl.customer.service.IPrjBillApplyService;
import cn.fl.customer.service.IPrjBillBscInfoService;
import cn.fl.customer.vo.PrjBillBscInfoVO;
import com.alibaba.fastjson.JSON;
import fl.customer.facade.invoice.condition.SearchValidInvoiceQueryCondition;
import fl.customer.facade.invoice.constant.PrjBillApplyConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.IPrjBillFeeRService;
import cn.fl.customer.vo.PrjBillFeeRVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysDictionaryService;
import fl.customer.facade.invoice.condition.PrjBillFeeRQueryCondition;

/**
 * @Description: 票据-费用关系表 控制层
 */
@Controller
@RequestMapping("/invoice/prjbillfeer")
public class PrjBillFeeRController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PrjBillFeeRController.class);

	/**
	 * PrjBillFeeR 服务层BEAN
	 */
	@Autowired
	private IPrjBillFeeRService prjBillFeeRService;
	
	@Autowired
	private ISysDictionaryService sysDictionaryService;

	@Autowired
    private IPrjBillBscInfoService prjBillBscInfoService;

	@Autowired
    private IPrjBillApplyService prjBillApplyService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("invoice/prjbillfeer/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到审核开票页面
	 */
	@RequestMapping(value = "/toAuditingPage.do", method = { RequestMethod.GET})
	public ModelAndView toAuditingPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
        String applyId = request.getParameter("applyId");
		// 2：打印；3：作废；4：冲红
		String flag = request.getParameter("flag");
		String mdf = request.getParameter("mdf");
        ModelAndView view = null;
		if ("2".equals(flag) || "3".equals(flag) || "4".equals(flag)) {
            view = new ModelAndView("customer/invoice/invoice4PrintInvalidRevert");
            String billWayCd = request.getParameter("billWayCd");
            if ("1".equals(billWayCd)) {
                // 电子发票
                view = new ModelAndView("customer/invoice/cstInvoiceElectronDetail");
            }
        } else {
            view = new ModelAndView("customer/invoice/cstInvoiceAuditing");
            List<KeyValueVO> feeTyps = this.prjBillApplyService.querySupportFeeTyp(PrjBillApplyConstant.BILL_WAY_CD_2);
            if (CollectionUtils.isNotEmpty(feeTyps)) {
                view.addObject("feeTyps", JSON.toJSON(feeTyps));
            }
        }
		view.addObject("id", id);
        view.addObject("applyId", applyId);
        view.addObject("flag", flag);
        view.addObject("mdf", mdf);
        PrjBillBscInfoVO prjBillBscInfoVO = this.prjBillBscInfoService.selectById(Long.valueOf(id));
        if (null != prjBillBscInfoVO) {
            view.addObject("billTypCd", prjBillBscInfoVO.getBillTypCd());
        }
        //获取票据类型
		try {
			List<String> codeGrpCdList = new ArrayList<>();
			codeGrpCdList.add(DictionaryConstant.CODE_PRJ_BILL_TYP_CD);
			codeGrpCdList.add(DictionaryConstant.CODE_GRP_CST_NP_BK_CD);
			//加入一个发票类型
			Map<String, List<KeyValueVO>> map = this.sysDictionaryService.getMultiKvList(CurrentThreadContext.getFlServiceSysCd(), CurrentThreadContext.getCurrentOrgCd(), codeGrpCdList);
			//开户银行
			List<KeyValueVO> bkCdList =  map.get(DictionaryConstant.CODE_GRP_CST_NP_BK_CD);
			if(CollectionUtils.isEmpty(bkCdList)){
				bkCdList = new ArrayList<>();
			}
            //开户银行
            List<KeyValueVO> billTypCdList =  map.get(DictionaryConstant.CODE_PRJ_BILL_TYP_CD);
            if(CollectionUtils.isEmpty(billTypCdList)){
                bkCdList = new ArrayList<>();
            }
            ListIterator<KeyValueVO> iterator = billTypCdList.listIterator();
            while (iterator.hasNext()) {
                if(PrjBillApplyConstant.BILL_TYP_CD_4.equals(iterator.next().getKey())){
                    iterator.remove();//删除操作
                }
            }
			view.addObject("selectBkCdList", bkCdList);
			view.addObject("prjBillStsCdList", billTypCdList);
		} catch (Exception e) {
			BaseLogUtils.error(logger, "toAuditingPage", "获取数据字典组数据失败." + e.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		BaseLogUtils.info(logger, "toAuditingPage", "跳转到审核开票页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	
	/**
	 * 到审核开票详情页面
	 */
	@RequestMapping(value = "/toAuditingDetailPage.do", method = { RequestMethod.GET})
	public ModelAndView toAuditingDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("customer/invoice/cstInvoiceAuditingDetail");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toAuditingDetailPage", "跳转到审核开票详情页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String applyId = request.getParameter("applyId");
        String bscInfoId = request.getParameter("bscInfoId");
        SearchValidInvoiceQueryCondition qc = new SearchValidInvoiceQueryCondition();
        if (StringUtils.isNotEmpty(bscInfoId)) {
            qc.setBillId(Long.valueOf(bscInfoId));
        }
        if (StringUtils.isNotEmpty(applyId)) {
            qc.setApplyId(Long.valueOf(applyId));
        }
//		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
//		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		List<PrjBillFeeRVO> list = this.prjBillFeeRService.searchBillFeeListByApplyId(qc);
        for (PrjBillFeeRVO prjBillFeeRVO : list) {
            Integer payPd = prjBillFeeRVO.getPayPd();
            String feeTypCdNm = prjBillFeeRVO.getFeeTypCdNm();
            if (0 < payPd) {
                prjBillFeeRVO.setFeeTypCdNm("第" + payPd + "期" + feeTypCdNm);
            }
        }
		ListPageVO<PrjBillFeeRVO> listPage = new ListPageVO<PrjBillFeeRVO>(list, list.size());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjBillFeeRService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	/**
	 * 把删除数据变成2, 2的数据不算删除数据,但是在申请的时候要把这个数据过滤为可以申请
	 */
	@RequestMapping(value = "/removeToHoldById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeToHoldById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjBillFeeRService.removeToHoldById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "操作数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "操作数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "操作数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	/**
	 * 把删除状态为2的数据变成0正常状态
	 */
	@RequestMapping(value = "/modifyHoldToNormalById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO modifyHoldToNormalById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.prjBillFeeRService.modifyHoldToNormalById(Long.valueOf(id));
			BaseLogUtils.info(logger, "modifyHoldToNormalById", "恢复数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyHoldToNormalById", "恢复数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifyHoldToNormalById", "恢复数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	
	
	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			PrjBillFeeRVO vo = this.prjBillFeeRService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		//String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjBillFeeRVO entity = null;
		try {
			entity = new PrjBillFeeRVO();
			Long id = this.prjBillFeeRService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjBillFeeRVO entity = null;
		try {
			entity = new PrjBillFeeRVO();
			entity.setId(Long.valueOf(id));
			boolean success = this.prjBillFeeRService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
}

